#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
@File    :  push_data_to_onenet.py
@Time    :  2022/05/02 19:21:06
@Author  :  HHLiang
@Contact :  sternapeg@qq.com
@Version :  1.0
@Desc    :  数据上传到云平台
'''

from config import config_run
from edp_sdk import *

import time

localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


# 以下设备和产品信息，请自行补全
# api_key = 'XXXXXXXXXXXXX'    # 设备APIkey
# product_id = 'XXXXXX'        # 产品ID
# device_id = 'XXXXXXXXX'      # 设备ID
# auth_info = 'XXXXXXXXXXXX'   # 鉴权信息

config = config_run('A1')
api_key = config[0]
product_id = config[1]
device_id = config[2]
auth_info = config[3]

host = config[4]
port = config[5]

# 创建Sockey连接
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接
s.connect((host, port))
# 发送登录报文， 并接收响应
conn_msg = gen_conn_msg(pid=product_id, auth_info=auth_info)
# print(conn_msg)
s.send(conn_msg)
# 接收响应并打印
resp = s.recv(1024)
print('设备注册结果：', resp)


def save_data_by_type1():
    # 构建JSON数据流
    dict = {
        'datastreams': [
            {
                'id': 'type1',
                'datapoints': [
                    {
                        'at': localtime,
                        'value': 33.61
                    }
                ]
            }
        ]
    }
    dt = json.dumps(dict)
    # print('---0---dt json: ', dt)

    # # 依据数据类型1 数据组包并上传
    t1_data = save_type1(dt, 1)
    # print('---1---t1_data: ', t1_data)
    # 上传数据
    s.send(t1_data)
    # print('t1_data', t1_data)
    # 接收反馈信息
    resp = s.recv(1024)
    print('recv', resp)
    # time.sleep(5)  #定时


def save_data_by_type3():
    # 构建JSON数据流
    data = {
        'type3': 33,
        'type3_test1': 25
    }
    data = json.dumps(data)
    # 调用SDK函数进行组包
    t3_data = save_type3(data, 1)
    # 上传数据
    s.send(t3_data)
    print('send t3_data: ', t3_data)
    # 接收反馈信息
    resp = s.recv(1024)
    print('recv: ', resp)
    # print('recv: ', resp.hex(), resp[-1])


def save_data_by_type4():
    # 构建JSON数据流
    data = {
        'type4': {localtime: 22.2},
        'type4_test2': {localtime: 33.3}
    }
    data = json.dumps(data)
    # 调用SDK函数进行组包
    t4_data = save_type4(data, 1)
    # 上传数据
    s.send(t4_data)
    print('send t4_data: ', t4_data)
    # 接收反馈信息
    resp = s.recv(1024)
    print('recv: ', resp)
    # print('recv: ', resp.hex(), resp[-1])


def save_data_by_type5():
    # 构建JSON数据流
    # data = ls
    # data = '#@type5#2022-05-19 12:00:00#12.3@102@pm2.5#89@10'
    data = ',;type5,2022-05-19 12:00:00,12.3;102;pm2.5,89;10'
    # 调用SDK函数进行组包
    t5_data = save_type5(data, 1)
    # 上传数据
    s.send(t5_data)
    print('send t5_data: ', t5_data)
    # 接收反馈信息
    resp = s.recv(1024)
    print('recv: ', resp)


if __name__ == '__main__':

    save_data_by_type1()
    save_data_by_type3()
    save_data_by_type4()
    save_data_by_type5()
